﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Lib.Common;
using SDT.Model;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using SDT.Lib.Helpers;
using System.IO;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 01/07/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Project)]
    public class ProjectController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /Project/

        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("project.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("project.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("project.CatID", "CatID", 0));
                    string strPub = UserState.getUserStateFromRequest("project.CurrentPubStatus", "CurrentPubStatus", "").ToString();
                    string strHotYN = UserState.getUserStateFromRequest("Project.CurrentHotYN","CurrentHotYN","").ToString();
                    string keyword = UserState.getUserStateFromRequest("project.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("project.pageSize", "PageSize", 20).ToString());
                    int? currentHotYN = null;
                    if (!string.IsNullOrEmpty(strHotYN)) currentHotYN = Convert.ToInt32(strHotYN);
                    int? currentPub = null;
                    if (!string.IsNullOrEmpty(strPub))
                        currentPub = Convert.ToInt32(strPub);

                    var pros = eDataContext.Projects
                        .Where(p => (catID > 0 ? p.CatID == catID : true))
                        .Where(p => currentPub.HasValue ? p.PubYN == (currentPub.HasValue && currentPub.Value == 1 ? true : false) : true)
                        .Where(p => currentHotYN.HasValue ? p.HotYN == (currentHotYN.HasValue && currentHotYN.Value == 1 ? true : false): true)
                        .Where(p => (string.IsNullOrEmpty(keyword) ? true :
                            (p.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
                            p.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
                            p.Title.ToLower().Contains(keyword.ToLower().Trim())
                        )))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    List<TreeNodeItem> listTree = eDataContext.ProjectCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = catID > 0 ? new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, catID) :
                                                                new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new ProjectViewModels
                    {
                        Projects = pros,
                        Categories = categories,
                        CurrentCat = catID,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProjectRootUrl
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Project/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                    Project p = eDataContext.Projects.Where(pr => pr.ID == id).FirstOrDefault();
                    List<TreeNodeItem> listTree = eDataContext.ProjectCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    List<ProjectCompanyType> ListCompanyType = eDataContext.ProjectCompanyTypes.ToList();
                    List<SelectListItem> ListCom = eDataContext.Companies
                                                 .Where(c => c.ActiveYN == true)
                                                 .Select(c => new SelectListItem()
                                                 {
                                                     Text = c.Name,
                                                     Value = c.ID.ToString()
                                                 }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    List<SelectListItem> listItem = eDataContext.ProjectLegalStatus
                                                    .Where(l => l.ActiveYN == true)
                                                    .Select(l => new SelectListItem()
                                                    {
                                                        Value = l.ID.ToString(),
                                                        Text = l.Name
                                                    }).ToList();
                    List<SelectListItem> listImageType = eDataContext.ProjectImageTypes
                                                         .Select(i => new SelectListItem()
                                                         {
                                                             Value = i.ID.ToString(),
                                                             Text = i.Name
                                                         }).ToList();
                    List<ProjectImage> listProImg = eDataContext.ProjectImages.Where(pi => pi.ProjectID == id).ToList();
                    List<ProjectCompanyMap> listPCM = eDataContext.ProjectCompanyMaps.Where(pm => pm.ProjectID == id).ToList();
                    var listTagID = eDataContext.ProjectTagMaps.Where(e => e.ProjectID == id).Select(e => e.TagID).ToList();
                    var listTag = eDataContext.Tags.ToList();
                    return View(new ProjectInputModels
                    {
                        Categories = categories,
                        ListLegalStatus = listItem,
                        CompanyType = ListCompanyType,
                        ListCompany = ListCom,
                        ListImageType = listImageType,
                        Project = p,
                        ListProjectImage = listProImg,
                        ListProjectCompanyMap = listPCM,
                        Tags = listTag,
                        ListTagID = listTagID,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProjectRootUrl + id.ToString()
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Project/Create

        public ActionResult Create()
        {
            try
            {
					List<SelectListItem> listC = eDataContext.Cities
											  .Select(c => new SelectListItem()
											  {
												  Value = c.ID.ToString(),
												  Text = c.Name
											  }).ToList();
                    List<TreeNodeItem> listTree = eDataContext.ProjectCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    List<ProjectCompanyType> ListCompanyType = eDataContext.ProjectCompanyTypes.ToList();
                    List<SelectListItem> ListCom = eDataContext.Companies
                                                 .Where(c => c.ActiveYN == true)
                                                 .Select(c => new SelectListItem()
                                                 {
                                                     Text = c.Name,
                                                     Value = c.ID.ToString()
                                                 }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    List<SelectListItem> listItem = eDataContext.ProjectLegalStatus
                                                    .Where(l => l.ActiveYN == true)
                                                    .Select(l => new SelectListItem()
                                                    {
                                                        Value = l.ID.ToString(),
                                                        Text = l.Name
                                                    }).ToList();
                    List<SelectListItem> listImageType = eDataContext.ProjectImageTypes
                                                         .Select(i => new SelectListItem()
                                                         {
                                                             Value = i.ID.ToString(),
                                                             Text = i.Name
                                                         }).ToList();
                    return View(new ProjectInputModels
                    {
                        Categories = categories,
                        ListLegalStatus = listItem,
                        CompanyType = ListCompanyType,
                        ListCompany = ListCom,
                        ListImageType = listImageType,
						ListCity =listC
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /Project/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ProjectInputModels m)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    m.Project.AddBy = UserManager.GetUserId();
                    m.Project.AddDate = DateTime.Now;
                    m.Project.ModifyDate = DateTime.Now;
                    eDataContext.Projects.InsertOnSubmit(m.Project);
                    eDataContext.SubmitChanges();
                    List<ProjectCompanyType> ListCompanyType = eDataContext.ProjectCompanyTypes.ToList();
                    // map company and type
                    foreach (var item in ListCompanyType)
                    {
                        if (!string.IsNullOrEmpty(Request[m.CompanyTypeID + item.ID]))
                        {
                            ProjectCompanyMap pComMap = new ProjectCompanyMap();

                            pComMap.ProjectID = m.Project.ID;
                            pComMap.TypeID = item.ID;
                            pComMap.CompanyID = int.Parse(Request[m.CompanyTypeID + item.ID]);

                            eDataContext.ProjectCompanyMaps.InsertOnSubmit(pComMap);
                            eDataContext.SubmitChanges();
                        }
                    }

                    // Update file
                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Project.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProjectRootPath), "" + m.Project.ID);
                    }
                    // insert ProjectTagMap Vietlv(10/08/2011)   
                    var projectTagID = Request["TagID"] != null ? Request["TagID"].ToString() : string.Empty;
                    if (projectTagID != string.Empty)
                    {
                        var arr = projectTagID.Split(',');
                        if (arr.Length > 0)
                        {
                            for (int i = 0; i < arr.Length; i++)
                            {
                                var itemID = Utils.ParseInt(arr[i]);
                                if (itemID > 0)
                                {
                                    ProjectTagMap proTagMap = new ProjectTagMap();
                                    proTagMap.ProjectID = m.Project.ID;
                                    proTagMap.TagID = itemID;

                                    eDataContext.ProjectTagMaps.InsertOnSubmit(proTagMap);
                                    eDataContext.SubmitChanges();
                                }
                            }

                        }
                    }

                    eDataContext.SubmitChanges();
                    eDataContext.Transaction.Commit();
                    eDataContext.Transaction.Dispose();
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Project/AddImage

        public ActionResult AddImage(int id, FormCollection frm)
        {
            id = int.Parse(frm["ProjectID"]);
            try
            {
                    #region Upload File
                    foreach (string inputTagName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[inputTagName];
                        if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                        {
                            ProjectImage pI = new ProjectImage();
                            UpdateModel(pI);
                            var index = inputTagName.Substring(inputTagName.IndexOf("fileInput") + 9);
                            
                            pI.ImagePath = file.FileName;
                            eDataContext.ProjectImages.InsertOnSubmit(pI);
                            eDataContext.SubmitChanges();
                            string filePath = string.Empty;

                            if (!Directory.Exists(Settings.Default.SiteRootPath + Settings.Default.ProjectRootPath + pI.ProjectID + "\\" + pI.ImageTypeID))
                            {
                                // If it doesn't then we just create it before going any further
                                Directory.CreateDirectory(Settings.Default.SiteRootPath + Settings.Default.ProjectRootPath + pI.ProjectID +"\\"+ pI.ImageTypeID);
                            }
                            //filePath = Path.Combine(Settings.Default.SiteRootPath + Settings.Default.ProjectRootPath + pI.ProjectID + pI.ImageTypeID + "\\" + file.FileName);
                            filePath = Settings.Default.SiteRootPath + Settings.Default.ProjectRootPath + pI.ProjectID + "\\" + pI.ImageTypeID + "\\" + file.FileName;
                            file.SaveAs(filePath);
                        }
                    }
                    #endregion

                    return RedirectToAction("Edit", new
                    {
                        id = id
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return RedirectToAction("Edit", new
                {
                    id = id
                });
            }
        }

        //
        // GET: /Project/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                    Project p = eDataContext.Projects.Where(pr => pr.ID == id).FirstOrDefault();
					List<SelectListItem> listC = eDataContext.Cities
											  .Select(c => new SelectListItem()
											  {
												  Value = c.ID.ToString(),
												  Text = c.Name
											  }).ToList();
					List<SelectListItem> listD = eDataContext.Districts
												 .Where(d => d.CityID == p.CityID)
												 .Select(d => new SelectListItem()
												 {
													 Value = d.ID.ToString(),
													 Text = d.Name
												 }).ToList();

                    List<TreeNodeItem> listTree = eDataContext.ProjectCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    List<ProjectCompanyType> ListCompanyType = eDataContext.ProjectCompanyTypes.ToList();
                    List<SelectListItem> ListCom = eDataContext.Companies
                                                 .Where(c => c.ActiveYN == true)
                                                 .Select(c => new SelectListItem()
                                                 {
                                                     Text = c.Name,
                                                     Value = c.ID.ToString()
                                                 }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    List<SelectListItem> listItem = eDataContext.ProjectLegalStatus
                                                    .Where(l => l.ActiveYN == true)
                                                    .Select(l => new SelectListItem()
                                                    {
                                                        Value = l.ID.ToString(),
                                                        Text = l.Name
                                                    }).ToList();
                    List<SelectListItem> listImageType = eDataContext.ProjectImageTypes
                                                         .Select(i => new SelectListItem()
                                                         {
                                                             Value = i.ID.ToString(),
                                                             Text = i.Name
                                                         }).ToList();
                    List<ProjectImage> listProImg = eDataContext.ProjectImages.Where(pi => pi.ProjectID == id).ToList();
                    List<ProjectCompanyMap> listPCM = eDataContext.ProjectCompanyMaps.Where(pm => pm.ProjectID == id).ToList();
                    // insert by Vietlv (10/08/2011) 
                    var listCurrentTag = (from n in eDataContext.ProjectTagMaps where n.ProjectID == id select n.Tag.Keyword).ToList();
                    var curentTag = "";
                    foreach (var itemtag in listCurrentTag)
                        {
                            curentTag += itemtag.ToString() + ",";
                        }

                    return View(new ProjectInputModels
                    {
                        Categories = categories,
                        ListLegalStatus = listItem,
                        CompanyType = ListCompanyType,
                        ListCompany = ListCom,
                        ListImageType = listImageType,
                        Project = p,
                        ListProjectImage = listProImg,
                        ListProjectCompanyMap = listPCM,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProjectRootUrl + id.ToString(),
						ListCity = listC,
						ListDistrict = listD,
                        CurrentListTag = curentTag
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Project/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, ProjectInputModels m)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    m.Project = eDataContext.Projects.Where(p => p.ID == id).FirstOrDefault();
                    UpdateModel(m);
                    m.Project.ModifyBy = UserManager.GetUserId();
                    m.Project.ModifyDate = DateTime.Now;
                    eDataContext.SubmitChanges();

                    // xoa company map project
                    var listItem = eDataContext.ProjectCompanyMaps.Where(pm => pm.ProjectID == id).ToList();
                    eDataContext.ProjectCompanyMaps.DeleteAllOnSubmit(listItem);
                    eDataContext.SubmitChanges();

                    List<ProjectCompanyType> ListCompanyType = eDataContext.ProjectCompanyTypes.ToList();
                    // map company and type
                    foreach (var item in ListCompanyType)
                    {
                        if (!string.IsNullOrEmpty(Request[m.CompanyTypeID + item.ID]))
                        {
                            ProjectCompanyMap pComMap = new ProjectCompanyMap();

                            pComMap.ProjectID = m.Project.ID;
                            pComMap.TypeID = item.ID;
                            pComMap.CompanyID = int.Parse(Request[m.CompanyTypeID + item.ID]);

                            eDataContext.ProjectCompanyMaps.InsertOnSubmit(pComMap);
                            eDataContext.SubmitChanges();
                        }
                    }

                    // Update file
                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Project.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ProjectRootPath), "" + m.Project.ID);
                    }
                    // Delete old ProjectTagMap
                    var listProjectTagMap = eDataContext.ProjectTagMaps.Where(e => e.ProjectID == id).ToList();
                    if (listProjectTagMap != null && listProjectTagMap.Count > 0) eDataContext.ProjectTagMaps.DeleteAllOnSubmit(listProjectTagMap);
                    eDataContext.SubmitChanges();
                    // insert ProjectTagMap by Vietlv(10/08/2011)
                    var stringTagMap = Request["TagName"].ToString();
                    if (stringTagMap != null && stringTagMap != string.Empty)
                    {
                       // var listTagKeyword = string.IsNullOrEmpty(stringTagMap) ? null : stringTagMap.Split(',');
                        foreach (var itemTag in eDataContext.Tags)
                        {
                            if (stringTagMap.Contains(itemTag.Keyword))
                            {
                                var itemProjectTag = new ProjectTagMap();
                                itemProjectTag.ProjectID = id;
                                itemProjectTag.TagID = itemTag.ID;
                                eDataContext.ProjectTagMaps.InsertOnSubmit(itemProjectTag);
                            }
                        }
                    }
                    
                    eDataContext.SubmitChanges();
                    eDataContext.Transaction.Commit();
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /ProjectCategory/Delete/5

        public ActionResult Delete(int id)
        {
            try
            {
                    Project p = eDataContext.Projects.Where(pr => pr.ID == id).FirstOrDefault();
                    return View(p);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        
        //
        // POST: /ProjectCategory/Delete/5
        /// <summary>
        /// Modified by: Vietlv
        /// Date:10/08/2011
        /// Delete other table have relationship with Project table when click delete one Project
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {

            try
            {
                Project p = eDataContext.Projects.Where(pr => pr.ID == id).FirstOrDefault();
                //Delete ProjectCompanyMap
                var listProjectCompanyMap = eDataContext.ProjectCompanyMaps.Where(e => e.ProjectID == id).ToList();
                    eDataContext.ProjectCompanyMaps.DeleteAllOnSubmit(listProjectCompanyMap);
                // Delete File ProjectImage
                var listProjectImage = eDataContext.ProjectImages.Where(e => e.ProjectID == id).ToList();
                foreach (var itemProjectImage in listProjectImage)
                {
                    foreach (var itemImageType in eDataContext.ProjectImageTypes)
                    {
                            var path = Settings.Default.SiteRootPath + Settings.Default.ProjectRootPath + p.ID + "\\"+ itemImageType.ID+ "\\" + itemProjectImage.ImagePath;
                            Uploads.DeleteFile(path);
                    }
                }
                // Delete ProjectImage
                eDataContext.ProjectImages.DeleteAllOnSubmit(listProjectImage);
                // Delete title Image of project
                    var pathImageTitle = Settings.Default.SiteRootPath + Settings.Default.ProjectRootPath + id.ToString() + "_" + p.ImagePath;
                    Uploads.DeleteFile(pathImageTitle);
                // Delete ProjectTagMap
                    var proTag = eDataContext.ProjectTagMaps.Where(e => e.ProjectID == id).ToList();
                    eDataContext.ProjectTagMaps.DeleteAllOnSubmit(proTag);

                // Delete current Project    
                    if (p != null)
                    {
                        eDataContext.Projects.DeleteOnSubmit(p);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
